package com.alibaba.dingtalk.openapi.helper;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.newmessage.utils.HttpHelper;
import com.alibaba.dingtalk.openapi.vo.workrecord.CancelTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcess;
import com.alibaba.dingtalk.openapi.vo.workrecord.DeleteProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveFakeProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveProcess;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.UpdateTask;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 钉钉待办方法类
 * 钉钉文档：https://open-doc.dingtalk.com/microapp/serverapi3/few6dd
 *
 * @author xingxing.xiao
 * No one asked me if I wanted to do it.
 */
public class DingtalkWorkrecordHelper {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkWorkrecordHelper.class);

    private static Random random = new Random();
    /**
     * 返回参数封装成对象
     */
    @Setter
    @Getter
    @ToString
    public static class BaseResponse {
        /**
         * 返回码
         */
        Long errcode;

        /**
         * 对返回码的文本描述内容
         */
        String errmsg;

        /**
         * 无意义
         */
        String request_id;
    }

    /**
     * 模板
     */
    @Setter
    @Getter
    @ToString
    public static class ProcessTemplateResponse extends BaseResponse {

        private ProcessTemplate result;

        @Getter
        @Setter
        @ToString
        public static class ProcessTemplate {

            /**
             * 模板的唯一码
             */
            private String process_code;
        }
    }

    /**
     * 实例
     */
    @Setter
    @Getter
    @ToString
    public static class ProcessInstanceResponse extends BaseResponse {

        private ProcessInstance result;
        private boolean success;

        @Getter
        @Setter
        @ToString
        public static class ProcessInstance {

            /**
             * 实例id
             */
            private String process_instance_id;
        }
    }

    /**
     * 任务
     */
    @Setter
    @Getter
    @ToString
    public static class TaskResponse extends BaseResponse {

        /**
         * 任务列表
         */
        private List<Task> tasks;

        @Getter
        @Setter
        @ToString
        public static class Task {

            /**
             * 任务id，更新任务接口需要用到
             */
            private Long task_id;

            /**
             * 任务执行人
             */
            private String userid;
        }
    }

    /**
     * 创建或更新待办模板
     *
     * @param pojo
     * @param accessToken
     * @return process_code	模板的唯一码
     * @throws OApiException
     */
    public static ProcessTemplateResponse saveWorkrecordTemplate(SaveProcess pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/save?access_token=" + accessToken;
        ProcessTemplateResponse templateResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
        } catch (OApiException e) {
            LOG.error("saveWorkrecordTemplate 出错：", e);
        }

        if (Objects.nonNull(response)) {
            templateResponse = JSONObject.parseObject(response.toJSONString(), ProcessTemplateResponse.class);
        }
        return templateResponse;
    }

    /**
     * 删除待办模板
     * 钉钉返回：{"success":true,"request_id":"sq3rrsdivq51"}
     */
    public static BaseResponse deleteWorkrecordTemplate(DeleteProcess pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/delete?access_token=" + accessToken;
        BaseResponse baseResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
        } catch (OApiException e) {
            LOG.error("deleteWorkrecordTemplate 出错：", e);
        }

        if (Objects.nonNull(response)) {
            baseResponse = JSONObject.parseObject(response.toJSONString(), BaseResponse.class);
        }
        return baseResponse;
    }

    /**
     * 创建钉钉待办实例
     * 钉钉返回 {"errcode":0,"result":{"process_instance_id":"9d2d0a25-10bf-40d0-a484-6807f84d2449"},"success":true,"request_id":"zbbezg8ranbb"}
     *
     * @return process_instance_id	实例id
     */
    public static ProcessInstanceResponse createWorkrecordInstance(SaveFakeProcessInstance pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/create?access_token=" + accessToken;
        ProcessInstanceResponse processInstanceResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.createWorkrecordInstance="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("createWorkrecordInstance 出错：", e);
        }

        if (Objects.nonNull(response)) {
            processInstanceResponse = JSONObject.parseObject(response.toJSONString(), ProcessInstanceResponse.class);
        }
        return processInstanceResponse;
    }

    /**
     * 更新实例状态
     * 钉钉返回：{"errcode":0,"request_id":"6v5v0braxabi"}
     */
    public static BaseResponse updateWorkrecordInstance(UpdateProcessInstance pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/update?access_token=" + accessToken;
        BaseResponse baseResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.updateWorkrecordInstance="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("updateWorkrecordInstance 出错：", e);
        }

        if (Objects.nonNull(response)) {
            baseResponse = JSONObject.parseObject(response.toJSONString(), BaseResponse.class);
        }
        return baseResponse;
    }

    /**
     * 删除待办实例
     */
    public static BaseResponse deleteWorkrecordInstance(DeleteProcessInstance instance, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/delete?access_token=" + accessToken;
        BaseResponse baseResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, instance);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.deleteWorkrecordInstance="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("deleteWorkrecordTemplate 出错：", e);
        }

        LOG.info("pojo: " + JSON.toJSONString(instance));
        if (Objects.nonNull(response)) {
            LOG.info("deleteWorkrecordInstance: " + response.toJSONString());
            baseResponse = JSONObject.parseObject(response.toJSONString(), BaseResponse.class);
        }
        return baseResponse;
    }

    /**
     * 创建钉钉待办任务
     * 钉钉返回：{"errcode":0,"tasks":[{"task_id":61732939152,"userid":"184742440432470774"}],"request_id":"10b62r2dcs8bd"}
     */
    public static TaskResponse createWorkrecordTask(SaveTask pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/task/create?access_token=" + accessToken;
        TaskResponse taskResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.createWorkrecordTask="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("createWorkrecordTask 出错：", e);
        }

        if (Objects.nonNull(response)) {
            taskResponse = JSONObject.parseObject(response.toJSONString(), TaskResponse.class);
        }
        return taskResponse;
    }

    /**
     * 更新任务状态
     * 钉钉返回：{"errcode":0,"request_id":"xbax91t77zjw"}
     */
    public static BaseResponse updateWorkrecordTask(UpdateTask pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/task/update?access_token=" + accessToken;
        BaseResponse baseResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.updateWorkrecordTask="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("updateWorkrecordTask 出错：", e);
        }

        if (Objects.nonNull(response)) {
            baseResponse = JSONObject.parseObject(response.toJSONString(), BaseResponse.class);
        }
        return baseResponse;
    }

    /**
     * 更新任务状态
     * 钉钉返回：{"errcode":0,"request_id":"xbax91t77zjw"}
     */
    public static void asyncUpdateWorkrecordTask(UpdateTask pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/task/update?access_token=" + accessToken;
        try {
            HttpHelper.httpAsyncPost(dingtalkUrl, pojo);
        } catch (Exception e) {
            LOG.error("updateWorkrecordTask 出错：", e);
        }
    }
    /**
     * 批量取消任务
     * 使用场景：在或签等场景下，开发者需要批量把正在运行中的任务设置为CANCELED，可以调用此接口
     * 钉钉返回：{"errcode":0,"request_id":"w2umsvqrxf6d"}
     */
    public static BaseResponse cancelWorkrecordTaskgroup(CancelTask pojo, String accessToken) {
        String dingtalkUrl = Env.OAPI_HOST + "/topapi/process/workrecord/taskgroup/cancel?access_token=" + accessToken;
        BaseResponse baseResponse = null;
        JSONObject response = null;
        try {
            response = HttpHelper.httpPost(dingtalkUrl, pojo);
            LOG.info("com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper.cancelWorkrecordTaskgroup="+ JSON.toJSONString(response));
        } catch (OApiException e) {
            LOG.error("cancelWorkrecordTaskgroup 出错：", e);
        }

        if (Objects.nonNull(response)) {
            baseResponse = JSONObject.parseObject(response.toJSONString(), BaseResponse.class);
        }
        return baseResponse;
    }

    /**
     * 随机数
     *
     * @param length 随机字符串的长度
     * @return
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

}
